package com.summer.campussct.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.summer.campussct.pojo.User;
import com.summer.campussct.mapper.UserMapper;
import com.summer.campussct.pojo.dto.*;
import com.summer.campussct.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.campussct.utils.FileUtil;
import com.summer.campussct.utils.JwtUtil;
import com.summer.campussct.utils.PasswordUtil;
import com.summer.campussct.utils.UserIdHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户商户信息表，敏感信息可能会加密存储，因此设置为256个字符 服务实现类
 * </p>
 *
 * @author Mr.Chen
 * @since 2024-04-21
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserMapper userMapper;

    @Resource
    private FileUtil fileUtil;

    @Value("${file-position.userAvatarPath}")
    private String userAvatarPath;

    @Override
    public User getUserDetailsById(long id) {
        return this.getOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, id)
                .select(User::getId, User::getNickname, User::getAvatar, User::getPhone, User::getWechat));
    }

    @Override
    public RestResult getUserDetails(long id) {
        User user = getOne(new LambdaQueryWrapper<User>()
                .select(User::getId,
                        User::getAccount,
                        User::getNickname,
                        User::getAvatar,
                        User::getPhone,
                        User::getType)
                .eq(User::getId, id));
        if (user == null){
            throw new RuntimeException("用户不存在");
        }
        return RestResult.success(user);
    }

    @Override
    public RestResult register(Map<String, String> registerForm) {
        // 密码加密
        String password = registerForm.get("password");
        String encrypt = PasswordUtil.encrypt(password);

        // 新增用户
        User user = new User();
        String account = registerForm.get("account");
        user.setAccount(account);
        user.setNickname(account);
        user.setPassword(encrypt);
        user.setType(1); // 个人用户
        user.setRoleId(2L); // 普通用户

        this.save(user);
        return RestResult.success();
    }

    @Override
    public RestResult modifyAvatar(MultipartFile file) {
        String url = null;
        try {
            url = fileUtil.saveToDest(file, userAvatarPath);
        } catch (IOException e) {
            System.err.println("上传头像失败");
            throw new RuntimeException(e);
        }

        //查询原头像
        User user = this.getOne(new LambdaQueryWrapper<User>()
                .select(User::getAvatar)
                .eq(User::getId, UserIdHolder.getId()));

        // 更新头像
        if (!this.update(new LambdaUpdateWrapper<User>()
                .set(User::getAvatar, url)
                .eq(User::getId, UserIdHolder.getId()))) {
            throw new RuntimeException("修改头像失败");
        }

        if (user != null && user.getAvatar() != null){
            String originalAvatar = user.getAvatar();
            // 将源头像删除
            try {
                fileUtil.deleteFile(originalAvatar);
            } catch (IOException e) {
                System.err.println("删除源头像失败");
                throw new RuntimeException(e);
            }
        }
        return RestResult.success(url);
    }

    @Override
    public RestResult getPermRange(long uid) {
        List<PermissionTuple> permissionTupleList = userMapper.getPermRangeById(uid);
        return RestResult.success(permissionTupleList);
    }

    @Override
    public RestResult login(Map<String, String> loginForm) {
        //1. 判断用户名密码是否正确
        UserDto userDto = userMapper.loginTest(loginForm);
        // 2. 用户不存在或密码错误则返回失败信息
        if (userDto == null) {
            return RestResult.error("用户不存在");
        }
        String password = userDto.getPassword();
        boolean isTrue = PasswordUtil.check(loginForm.get("password"), password);
        if (!isTrue){
            return RestResult.error("密码错误");
        }

        //3. 根据用户id和权限列表生成jwt
        UserIdWithPermList userIdWithPermList = new UserIdWithPermList();
        userIdWithPermList.setUserId(userDto.getId());
//        userIdWithPermList.setPermList(userDto.getPermList());
        userIdWithPermList.setPermissionTupleList(userDto.getPermissionTupleList());

        String jwt = jwtUtil.generateJwtToken(JSONUtil.toJsonStr(userIdWithPermList), 3600 * 24);

        return RestResult.success(jwt);
    }

    @Override
    public RestResult getUserInfo(long userId) {
        // 根据id查询用户信息
        User user = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, userId)
                .select(User::getId,
                        User::getNickname,
                        User::getAvatar,
                        User::getPhone,
                        User::getPosition,
                        User::getRoleId));
        if (user == null){
            throw new RuntimeException("用户不存在");
        }
        return RestResult.success(user);
    }

    @Override
    public RestResult modify(User user) {
        String nickname = user.getNickname();
        String position = user.getPosition();
        String phone = user.getPhone();
        boolean update = update(new LambdaUpdateWrapper<User>()
                .set(nickname != null && !"".equals(nickname),User::getNickname, nickname)
                .set( position != null && !"".equals(position),User::getPosition, position)
                .set( phone != null && !"".equals(position),User::getPhone, phone)
                .eq(User::getId, user.getId()));
        if (!update){
            throw new RuntimeException("修改个人信息失败");
        }
        return RestResult.success();
    }

    @Override
    public RestResult getListCondition(UserQueryParam userQueryParam) {
        Integer status = userQueryParam.getStatus();
        Integer type = userQueryParam.getType();
        String keyWord = userQueryParam.getKeyWord();
        Integer currentPage = userQueryParam.getCurrentPage();
        Integer pageSize = userQueryParam.getPageSize();
        // 如果不传递分页参数，默认查询1页十条
        if (currentPage == null) currentPage = 1;
        if (pageSize == null) pageSize = 10;

        // 查询条件
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>()
                .select(User::getId, User::getAvatar, User::getNickname, User::getPhone, User::getType, User::getStatus)
                .eq(status != null, User::getStatus, status)
                .eq(type != null, User::getType, status)
                .like(!"".equals(keyWord), User::getNickname, keyWord);
        Page<User> page = new Page<>(currentPage, pageSize);
        Page<User> result = this.page(page, lqw);

        Map<String, Object> map = new HashMap<>();
        map.put("records", result.getRecords());
        map.put("total", result.getTotal());

        return RestResult.success(map);
    }

    @Override
    public RestResult getRoleIdByUser(long id) {
        User one = this.getOne(new LambdaQueryWrapper<User>()
                .select(User::getRoleId)
                .eq(User::getId, id));
        return RestResult.success(one.getRoleId());
    }

    @Override
    public RestResult assignRole(User user) {
        if (!this.update(new LambdaUpdateWrapper<User>()
                .set(User::getRoleId, user.getRoleId())
                .eq(User::getId, user.getId()))) {
            throw new RuntimeException("分配角色失败");
        }
        return RestResult.success();
    }

    @Override
    public RestResult disableUser(long id, Integer status) {
        if (!this.update(new LambdaUpdateWrapper<User>()
                .set(User::getStatus, status)
                .eq(User::getId, id))) {
            throw new RuntimeException("禁用用户失败");
        }
        return RestResult.success();
    }

    @Override
    public RestResult addUser(User user) {
        //1. 密码加密
        String encryptPassword = PasswordUtil.encrypt(user.getPassword());
        user.setPassword(encryptPassword);

        //2. 转存头像
        String newUrl = fileUtil.transferSave(user.getAvatar(), userAvatarPath);
        user.setAvatar(newUrl);

        //3. 默认为用户分配普通用户角色
        if (user.getRoleId() == null) {
            user.setRoleId(2L);
        }

        //3. 新增用户
        this.save(user);
        return RestResult.success();
    }

    @Override
    public RestResult modifyUser(User user) {
        String oldAvatar = user.getAvatar();
        // 转存新头像
        String newUrl = fileUtil.transferSave(oldAvatar, userAvatarPath);
        // 删除旧头像
        if (!newUrl.equals(oldAvatar)){
            try {
                fileUtil.deleteFile(oldAvatar);
            } catch (IOException e) {
                log.error("删除旧头像失败，旧头像地址：{}", oldAvatar);
                throw new RuntimeException(e);
            }
        }
        user.setAvatar(newUrl);
        if (!this.update(new LambdaUpdateWrapper<User>()
                        .set(!"".equals(user.getNickname()), User::getNickname, user.getNickname())
                        .set(!"".equals(user.getPhone()), User::getPhone, user.getPhone())
                        .set(!"".equals(user.getAccount()), User::getAccount, user.getAccount())
                        .set(!"".equals(newUrl), User::getAvatar, newUrl)
                        .eq(User::getId, user.getId()))) {
            throw new RuntimeException("更新用户失败");
        }

        return RestResult.success();
    }

}
